<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import {
  getSampleStandardListApi,
  deleteSampleStandardApi,
  addSampleStandardApi,
  putSampleStandardApi,
  getSampleGroupOptionsApi
} from '@/api/check/sample'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { FemaleType } from '@/api/check/female/types'
import { ElButton } from 'element-plus'
import Write from './Write.vue'

const ids = ref<string[] | number[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getSampleStandardListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchSampleStandards)
    })
    return {
      list: res.data,
      total: res.count
    }
  },
  fetchDelApi: async () => {
    const res = await deleteSampleStandardApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchSampleStandards = ref({})
const setSearchSampleStandards = (params: any) => {
  searchSampleStandards.value = params
  getList()
}

const { t } = useI18n()

const sampleGroupOptions = ref([])
const getSampleGroupOptions = async () => {
  const res = await getSampleGroupOptionsApi()
  if (res) {
    sampleGroupOptions.value = res.data
    console.log('sampleGroupOptions', sampleGroupOptions)
  }
}
getSampleGroupOptions()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    fixed: true,
    type: 'selection',
    width: 80,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'index',
    label: t('common.index'),
    type: 'index',
    width: 80,
    fixed: true,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'standard',
    label: '标准件规范号'
  },
  {
    field: 'group_name',
    label: '组名称',
    form: {
      component: 'Select',
      componentProps: {
        clearable: false,
        style: {
          width: '100%'
        },
        filterable: true,
        options: sampleGroupOptions
      }
    }
  },
  {
    field: 'is_active',
    label: '启用标识',
    search: {
      component: 'Select',
      componentProps: {
        clearable: false,
        style: {
          width: '100%'
        },
        filterable: true,
        options: [
          {
            label: '是',
            value: 1
          },
          {
            label: '否',
            value: 0
          }
        ]
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        clearable: false,
        style: {
          width: '100%'
        },
        filterable: true,
        options: [
          {
            label: '是',
            value: 1
          },
          {
            label: '否',
            value: 0
          }
        ]
      },
      value: 1
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.is_active ? '是' : '否'}</>
        }
      }
    }
  },
  {
    field: 'create_user',
    label: '创建人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'create_datetime',
    label: '创建时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('common.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      minWdith: 100,
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElButton onClick={() => action(data.row, 'edit')}>编辑</ElButton>
              {/* <ElButton type="danger" onClick={() => delData(data.row)}>
                {t('common.del')}
              </ElButton> */}
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<FemaleType | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('common.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)

const delData = async (row: FemaleType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: FemaleType) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: FemaleType, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.edit' : 'common.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res =
        actionType.value === 'add'
          ? await addSampleStandardApi(formData)
          : await putSampleStandardApi(formData)
      if (res) {
        dialogVisible.value = false
        getList()
      }
    } finally {
      saveLoading.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      :schema="allSchemas.searchSchema"
      @search="setSearchSampleStandards"
      @reset="setSearchSampleStandards"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('common.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('common.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      :fit="true"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="700px" max-height="180px">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :form-schema="allSchemas.formSchema"
    />

    <Detail
      v-if="actionType === 'detail'"
      :current-row="currentRow"
      :detail-schema="allSchemas.detailSchema"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
</template>
